<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="110px">
            <EdCreateCard :title="isUpdate ? '编辑' : '新增'">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-row class="width-100">
                        <el-col :span="6">
                            <el-form-item label="所属项目" prop="villageId" :rules="$validate.validates({required:true,msg:'请选择'})" >
                                <EdSelect v-model="form.villageId" ref="selectpatrol" :selectParams="villageNameParams"  @emit-select-value="projectChange" style="width:100%"></EdSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="联系人" prop="leaserName" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入联系人" v-model="form.leaserName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="联系电话" prop="leaserPhone" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入联系电话" v-model="form.leaserPhone"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <!-- /*车位所属选的是物业展示input框*/ -->
                        <el-col :span="6" v-if="value==1 || value==''"> 
                            <el-form-item label="车位编号" prop="parkingSpacesNo" :rules="$validate.validates({required:true,msg:'车位编号不能为空'})">
                               <el-input class="flex-input" placeholder="请输入车位编号" v-model="form.parkingSpacesNo"></el-input>
                            </el-form-item>
                        </el-col>
                         <!-- /*车位所属选的是住户输入手机号查询所有车位*/ -->
                        <el-col :span="6" v-if="value==2">
                            <el-form-item label="车位编号" prop="parkingSpacesNo" :rules="$validate.validates({required:true,msg:'车位编号不能为空'})">
                               <el-select
                                        v-model="form.parkingSpacesNo"
                                        filterable
                                        remote
                                        class="inputWidth224 marginLeft20"
                                        reserve-keyword
                                        @change="changeShop"
                                        placeholder="请输入手机号"
                                        style="width: 100%;"
                                        :remote-method="remoteMethod"
                                        :loading="loading">
                                    <el-option v-if="value==2" v-for="item in ParkingNos" :key="item" :label="item" :value="item"> </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="租金" prop="rent" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.rent">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">元/月</i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="车位所属" prop="parkingSpacesBelong" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <template>
                                    <el-radio-group v-model="form.parkingSpacesBelong" @change="changeRadio">
                                        <el-radio  label='1'>物业</el-radio>
                                        <el-radio  label='2'>住户</el-radio>
                                    </el-radio-group>
                                </template>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-80">
                        <el-col :span="24">
                            <el-form-item label="图片" prop="pics">
                                <el-upload
                                    accept=".jpg, .jpeg, .png, .gif"
                                    :action="action"
                                    list-type="picture-card"
                                    :limit="5"
                                    :multiple="true"
                                    :file-list="fileList"
                                    :before-upload="beforeImgUpload"
                                    :on-preview="handleImgPreview"
                                    :on-success="handleImgSuccess"
                                    :on-remove="handleImgRemove">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                            <p class="labelFont">请上传2M以内的图片，建议上传图片大小430px*430px,格式为jpeg、jpg、png、gif的图片，至多5张</p>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-80">
                        <el-col :span="12">
                            <el-form-item label="车位简介" prop="description" >
                                <el-input type="textarea" placeholder="请补充车位信息及租赁要求..." v-model="form.description" :rows="6"  maxlength="200" show-word-limit></el-input>
                                <!-- <EdTinymce ref="EdTinymce" v-model="form.description"></EdTinymce> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item class="form_btns">
                    <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" >确定</el-button>
                    <el-button class="ed-button ed_white_bottom" @click="$utilsSet.goBack($router)">取消</el-button>
                </el-form-item>
            </EdCreateCard>
            <EdConfirmDelete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue"></EdConfirmDelete>
        </el-form>
    </div>
</template>

<script>
    import EdTinymce from 'src/components/EdTinymce.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdDateTimeRange from 'src/components/EdDateTimeRange.vue'
    import EdLazyCascader from 'src/components/EdLazyCascader.vue'
    import EdDateTimePickerRange from 'src/components/EdDateTimePickerRange.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import EdCascader from 'src/components/EdCascader.vue'
    import { defineComponent } from 'vue'
    import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
    import * as api from './api'  
    // import { houseRentInfo, houseRentAdd, houseRentUpdate } from "./api";
    import { getDictByCode } from "src/api/dictionaries";
    export default defineComponent({
        name: "companyCreate",
        components: { EdCreateCard, EdDateTimeRange, EdSelect, EdTinymce, EdCascader, EdDateTimePickerRange,EdLazyCascader,EdConfirmDelete },
        data(){
            return{
                form:{
                    villageId:'',
                    villageName:'',
                    leaserPhone:'',
                    leaserName: '',
                    parkingSpacesNo:'',
                    parkingNoId:'', /*选中的  */
                    rent:'',
                    parkingSpacesBelong:'',
                    pics:[],
                    description:''
                },
                loading:false,
                ParkingNos:[],
                ParkingNosList:[],
                isUpdate: false,
                fileList: [],
                action: '',
                dialogImageUrl: '',
                dialogVisible: false,
                villageNameParams:{
                    placeholder:"请选择项目",
                    options: [],
                    props: {label:"villageName", value:"villageId"},
                    // disabled:false
                },
                checkType:'',
                roomId:[],
                // changeDialog:false
                value:'' /*选住户还是物业之后的值 */
            }
        },
        activated(){
           this.projectList()
            this.action = this.$baseApi + "/infra/file/upload";
            // if(this.$route.query.id){
            //     // 编辑 
            //     this.isUpdate = true;
            //     this.parkingRentInfo();
            // }else {
              
            // }
        },
        deactivated(){
            this.form={}
            this.form.parkingSpacesNo=''
            // this.form.description = ''
            this.fileList = [];
            this.$refs['formRef'].resetFields()
            // this.$refs.timeRange.reset();
            // 清空editor的缓存
            if(this.$refs.EdTinymce) this.$refs.EdTinymce.$children[0].cache = '';
            this.productNumber_require = false;
        },
        methods:{
            onSubmit(formRef){
                this.$refs[formRef].validate((valid)=>{
                    if(valid){
                        // 车位添加查询是否有车位
                        this.villageNameParams.options.forEach((v, i)=>{
                            if(this.form.villageId==v.villageId){
                                this.form.villageName=v.villageName
                            }
                        })
                        api.checkContact({leaserName:this.form.leaserName,villageId:this.form.villageId,parkingSpacesNo:this.form.parkingSpacesNo}).then(res=>{
                            if (res.success) {
                                this.checkType = res.data.checkType
                                if(this.checkType==1){
                                    api.parkRentAdd(this.form).then(res=>{
                                        if(res.success){
                                            this.message.success({
                                                message: '新增成功',
                                                center: true,
                                                duration: 2000,
                                            })
                                            this.$utilsSet.goBack(this.$router);
                                            this.$refs.table.load()
                                            this.$refs['formRef'].resetFields()
                                        }
                                    })
                                }else if(this.checkType==2) {
                                    this.$refs.confirmDeleteRef.open('操作确认',"住户信息或车位信息不存在，是否继续发布？")
                                }
                            }
                        })
                    }
                })
            },
            // 匹配直接调接口
            confirmDeleteTrue(){
                api.parkRentAdd(this.form).then(res=>{
                    if(res.success){
                        this.message.success({
                            message: '新增成功',
                            center: true,
                            duration: 2000,
                        })
                        this.$utilsSet.goBack(this.$router);
                        this.$refs.table.load()
                        this.$refs['formRef'].resetFields()
                    }
                })
                
            },
             // 图片 上传前
            beforeImgUpload(file){
                // console.log('before-->', file)
                const fileType = file.name.split('.');
                const fileDate = fileType.slice(-1);
                if (['jpeg', 'jpg', 'png', 'gif'].indexOf(fileDate[0]) < 0) {
                    this.$message.error('仅支持格式：.jpg、.png、.gif!');
                    return false
                }
                const isLt5M = file.size / 1024 /1024 < 2;
                if (!isLt5M) {
                    return this.$message.error('上传文件大小不能超过 2MB!');
                }
                // return isLt5M;
                return true;
            },
            // 图片 上传成功
            handleImgSuccess(response, file, fileList){
                let res = file.response;
                if(res&&res.success == true){
                   this.form.pics.push(res['data'])
                }
            },
            // 图片 删除
            handleImgRemove(file, fileList) {
                this.form.pics = fileList&&fileList.map(v=>{
                    return v['url']
                })
            },
            // 图片 预览
            handleImgPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            // emitCascaderValue(data){
            //     let arr = [];
            //     arr.push(data&&data[data.length-1]);
            //     this.form.roomId = arr;
            //     // this.form.ownerId = '';
            //     if(data.length) this.getresidentsByRoomId(data[data.length-1]);
            // },
            // getresidentsByRoomId(roomId){
            //     api.getresidentsByRoomId(roomId).then(res => {
            //         if(res.success == true) {
            //             this.form.contacts = res.data.contacts;
            //             this.form.contactPhone = res.data.contactPhone;
            //         }
            //     })
            // },
            projectList(){
                api.projectList({page:1,pageSize:999999}).then(response => {
                    if(response.success) {
                        let options = response.data.records.map(x=>{return {villageName:x.villageName,villageId:x.villageId}})
                        this.villageNameParams.options=options
                    }
                })
            },
            projectChange(row){
                console.log('row',row);
                let options = this.villageNameParams.options.find(x=>{
                    return x.villageId == row
                })
                console.log('options',options);
                this.form.villageName = options.villageName
                this.form.villageId = options.villageId
            },
            changeRadio(val){
                console.log('val',val);
                // val等于表示是物业
                if(val==1){
                    this.value = 1
                    this.ParkingNos = []
                    this.form.parkingSpacesNo=''
                } else if(val==2){
                    this.value = 2
                }
            },
            remoteMethod(query) {
                if (query !== '') {
                    this.ParkingNoList(query);
                } else {
                    this.ParkingNos = [];
                    this.form.parkingSpacesNo=''
                }
            },
            changeShop(val){
                // for (let i=0;i<this.ParkingNos.length;i++){
                //     // if(this.ParkingNos[i].id == val){
                //         console.log('this.ParkingNos[i]',this.ParkingNos[i]);
                //         this.form.parkingSpacesNo = this.ParkingNos[i];
                //         // this.form.parkingSpacesNo = this.ParkingNos[i]
                //     // }else {
                //     //     this.form.parkingSpacesNo=''
                //     // }
                // }
            },
            ParkingNoList(query){
                console.log('query1',query);
                api.checkParkingNoList({phone:query,page: 1,villageId:this.form.villageId, pageSize: 999}).then(response => {
                    if(response.success) {
                        // this.ParkingNos = response.data;
                        this.ParkingNosList = response.data;
                        this.loading = true;
                        setTimeout(() => {
                            this.loading = false;
                            this.ParkingNos = this.ParkingNosList.filter(item => {
                                return item.toLowerCase()
                                    .indexOf(query.toLowerCase()) > -1;
                            });
                        }, 200);
                        query=''
                    }
                })
            },
            
        }
    })
</script>

<style scoped lang="scss">
    :deep {
        .el-form-item{
            .el-form-item__content{
                .el-input{
                    // width: 98% !important;
                    width: 100% !important;
                }
                
                .el-select{
                    width: 100% !important;
                    margin-left: 0% !important;
                    .el-input--suffix{
                        input {
                            width:100% !important;
                        }
                    }
                }
                 .el-cascader{
                    width: 100% !important;
                }
                .el-date-editor{
                    width: 100% !important;
                    // width: 98% !important;
                }
                .el-radio-group .el-radio.is-checked{
                    .el-radio__input{
                        .el-radio__inner{
                            border-color: #EED096;
                            background: #EED096;
                        }
                    }
                    .el-radio__label{
                        color: #EED096;
                    }
                }
                .el-radio-group .el-radio{
                    .el-radio__input{
                        .el-radio__inner:hover{
                            border-color: #EED096;
                        }
                    }
                }
            }
        }
    }

    .form_btns{
        // display: flex;
        // justify-content: flex-end;
        margin-left: 47px;
    }
    .labelFont{
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        color: #989898;
    }
</style>